package org.unt.logic;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class VelocityLogic {

	public static void generateFile(String template, File outputFile, Map<String, String> map) {

		VelocityEngine ve = new VelocityEngine();

		try {

			// This is necessary for loading the .vm from inside the jar of the plugin
			Properties props = new Properties();
			props.put("resource.loader", "class");
			props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

			ve.init(props);

		} catch (Exception e) {
			throw new RuntimeException("Cannot init VelocityEngine exception", e);
		}

		Template t;

		try {
			t = ve.getTemplate(template);
		} catch (Exception e) {
			throw new RuntimeException("Cannot get Velocity template exception", e);
		}

		VelocityContext context = new VelocityContext();

		for (Object key : map.keySet()) {

			context.put((String) key, map.get(key));
		}

		FileWriter writer = null;

		try {

			writer = new FileWriter(outputFile);
			t.merge(context, writer);

		} catch (IOException e) {
			throw new RuntimeException("Cannot write file exception", e);
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					throw new RuntimeException("Cannot close file exception", e);
				}
			}
		}
	}
}
